import pygame.font
from pygame.sprite import Group

from ship import Ship


class ScoreBoard:

    def __init__(self, ai_game):
        self.ai_game = ai_game
        self.screen = ai_game.screen
        self.screen_rect = ai_game.screen.get_rect()
        self.settings = ai_game.settings
        self.stats = ai_game.game_stats

        # 记分牌字体设置
        self.text_color = (250, 250, 250)
        self.font = pygame.font.SysFont(None, 40)

        # 渲染登记
        self.pre_level()
        # 渲染得分文字
        self.pre_score()
        # 渲染最高得分
        self.pre_high_score()
        # 渲染飞船编组
        self.pre_ships()

    def pre_level(self):
        level_str = f"Level: {self.stats.level}"
        self.level_image = self.font.render(level_str, True, self.text_color)
        # 分数下
        self.level_rect = self.level_image.get_rect()
        self.level_rect.right = self.screen_rect.right - 20
        self.level_rect.top = 20

    def pre_score(self):
        round_score = round(self.stats.score, -1)
        score_str = "Score: {:,}".format(round_score)
        self.score_image = self.font.render(score_str, True, self.text_color)
        # 右上角显示
        self.score_rect = self.score_image.get_rect()
        self.score_rect.right = self.screen_rect.right - 20
        self.score_rect.top = self.level_rect.bottom + 10

    def pre_high_score(self):
        round_score = round(self.stats.high_score, -1)
        high_score_str = "HighScore: {:,}".format(round_score)
        self.high_score_image = self.font.render(high_score_str, True, self.text_color)
        # 中间展示
        self.high_score_rect = self.high_score_image.get_rect()
        self.high_score_rect.right = self.screen_rect.right - 20
        self.high_score_rect.top = self.score_rect.bottom + 10

    def pre_ships(self):
        # 创建编组
        self.ships = Group()
        # 根据当前数量放入编组
        for num in range(self.stats.ship_life):
            ship = Ship(self.ai_game)
            ship.rect.x = 10 + num * ship.rect.width
            ship.rect.y = 20
            self.ships.add(ship)

    def show_score(self):
        self.screen.blit(self.score_image, self.score_rect)
        self.screen.blit(self.high_score_image, self.high_score_rect)
        self.screen.blit(self.level_image, self.level_rect)
        self.ships.draw(self.screen)

    def check_high_score(self):
        if self.stats.score > self.stats.high_score:
            self.stats.high_score = self.stats.score
            self.pre_high_score()
